package org.example.emp.interceptor;

import org.example.emp.common.JsonUtils;
import org.example.emp.common.JwtUtils;
import org.example.emp.common.RsaUtils;
import org.example.emp.pojo.Admin;
import org.example.emp.pojo.Result;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //跨域请求，会请求两次服务器。第一次请求是option
        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            return true;
        }


        //获取请求头中携带的token信息
        String token = request.getHeader("token");

        //使用公钥校验token
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
            Admin admin = (Admin) JwtUtils.getInfoFromToken(token, publicKey, Admin.class);
            if (admin.getUsername() == null && !admin.getUsername().equals("")) {
                //放行
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        //表明token校验失败
        //返回JSON到前端
        Result result = new Result(403,"无权访问");
        response.getWriter().write(JsonUtils.toString(result));
        return false;
    }
}
